package com.juyu.reader.author.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.juyu.reader.author.common.Constants;
import com.juyu.reader.author.common.PageDirective;
import com.juyu.reader.author.model.Author;
import com.juyu.reader.author.model.Book;
import com.juyu.reader.author.model.BookChapter;
import com.juyu.reader.author.model.BookTag;
import com.juyu.reader.author.model.Category;
import com.juyu.reader.author.model.Page;
import com.juyu.reader.author.model.Tag;
import com.juyu.reader.author.service.BookChapterService;
import com.juyu.reader.author.service.BookService;
import com.juyu.reader.author.service.BookTagService;
import com.juyu.reader.author.service.CategoryService;
import com.juyu.reader.author.service.TagService;
import com.juyu.reader.author.util.DES3;
import com.juyu.reader.author.util.Md5Util;
import com.juyu.reader.author.util.StringUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/book")
public class BookController extends BaseController {
	Logger logger = Logger.getLogger(BookController.class);
	@Autowired
	private BookService bookService;
	@Autowired
	private BookChapterService bookChapterService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private TagService tagService;
	@Autowired
	private BookTagService bookTagService;

	@RequestMapping("/list")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response, Page page) {
		Map<String, Object> attrMap = new HashMap<String, Object>();
		Author sessionAuthor = this.getSessionAuthor(request);
		Book findBook = new Book();
		findBook.setAuthorId(sessionAuthor.getAuthorId());
		findBook.setBookFlag(-1);// 查询完结或未完结的书籍
		page.setLimit(5);
		findBook.setLimit(page.getLimit());
		findBook.setPageNo(page.getPageNo());
		List<Book> bookList = bookService.findBook(findBook);
		// 设置最后章节显示
		for (Book b : bookList) {
			List<BookChapter> lastChapterList = bookChapterService.findBookChapterLastPublish(b.getBookId());
			if (lastChapterList.size() >= 1) {
				b.setBookLastChapter(lastChapterList.get(0).getChapterName());
			}
		}
		int count = bookService.countBook(findBook);
		attrMap.put("bookList", bookList);
		attrMap.put("recordCount", count);
		attrMap.put("page", page);
		attrMap.put("pageftl", new PageDirective(request));
		attrMap.put("sourceUrl", Constants.SOURCE_URL);
		return this.packModeAndView(request, "/bookList", null, attrMap);
	}

	@RequestMapping("add1")
	public ModelAndView bookAdd1(HttpServletRequest request, HttpServletResponse response) {
		return this.packModeAndView(request, "/bookAdd1", null, null);
	}

	@RequestMapping("add2")
	public ModelAndView bookAdd2(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> attrMap = new HashMap<String, Object>();
		String cTypeStr = request.getParameter("cType");
		int cType = 2;
		try {
			cType = Integer.valueOf(cTypeStr);
		} catch (Exception e) {
		}
		Category findCategory = new Category();
		findCategory.setCategoryPid(cType);// 1=男频，2=女频
		List<Category> categoryList = categoryService.findCategory(findCategory);
		List<Tag> tagList = tagService.findTag(new Tag());
		attrMap.put("categoryList", categoryList);
		attrMap.put("tagList", tagList);
		return this.packModeAndView(request, "/bookAdd2", null, attrMap);
	}

	@Transactional
	@RequestMapping("save")
	public ModelAndView bookSave(HttpServletRequest request, HttpServletResponse response, Book book) {
		Map<String, Object> attrMap = new HashMap<String, Object>();
		Author sessionAuthor = this.getSessionAuthor(request);
		Book insertBook = new Book();
		insertBook.setBookName(book.getBookName());
		insertBook.setBookStatus(2);// 默认是审核中
		insertBook.setBookDesc(book.getBookDesc());
		insertBook.setBookFree(2);// 收费书籍
		insertBook.setPlatformId(1);//所属CP（学而阅读=1）
		insertBook.setAuthorId(sessionAuthor.getAuthorId());
		insertBook.setBookCategoryId(book.getBookCategoryId());
		if (book.getBookImage().equals("2")) {
			insertBook.setBookImage("default/cover_2.jpg");
		} else if (book.getBookImage().equals("3")) {
			insertBook.setBookImage("default/cover_3.jpg");
		} else {
			insertBook.setBookImage("default/cover_1.jpg");
		}
		insertBook.setBookFlag(0);// 默认书籍是连载中
		insertBook.setBookImageType(0);// 表示官方图片
		bookService.insertBook(insertBook);
		// 保存书籍标签
		if (!StringUtil.isNullOrEmpty(book.getTagIds())) {
			String[] tagArray = book.getTagIds().split(",");
			for (int i = 0; i < tagArray.length; i++) {
				BookTag insertBookTag = new BookTag();
				insertBookTag.setBookId(insertBook.getBookId());
				insertBookTag.setTagId(Integer.valueOf(tagArray[i]));
				bookTagService.insertBookTag(insertBookTag);
			}
		}
		attrMap.put("bookId", insertBook.getBookId());
		return this.packModeAndView(request, "/bookAdd3", null, attrMap);
	}

	@RequestMapping("detail")
	public ModelAndView bookDetail(HttpServletRequest request, HttpServletResponse response, Book book) {
		Map<String, Object> attrMap = new HashMap<String, Object>();
		Author sessionAuthor = this.getSessionAuthor(request);
		Book findBook = new Book();
		findBook.setAuthorId(sessionAuthor.getAuthorId());
		findBook.setBookId(book.getBookId());
		findBook.setBookFlag(-1);
		List<Book> bookList = bookService.findBook(findBook);
		attrMap.put("bookId", book.getBookId());
		if (bookList.size() == 1) {
			attrMap.put("book", bookList.get(0));
			attrMap.put("sourceUrl", Constants.SOURCE_URL);
			BookTag findBookTag = new BookTag();
			findBookTag.setBookId(book.getBookId());
			List<BookTag> bookTagList = bookTagService.findBookTag(findBookTag);
			// String bookTagStrings = "";
			// for (BookTag bt : bookTagList) {
			// bookTagStrings = bookTagStrings + bt.getTagName() +
			// "&nbsp;&nbsp;";
			// }
			// attrMap.put("bookTagStrings", bookTagStrings);
			attrMap.put("bookTagList", bookTagList);
			return this.packModeAndView(request, "/bookDetail", null, attrMap);
		} else {
			return this.packModeAndView(request, "/error", "非法操作！", null);
		}

	}

	@RequestMapping("edit")
	public ModelAndView bookEdit(HttpServletRequest request, HttpServletResponse response, Book book) {
		Map<String, Object> attrMap = new HashMap<String, Object>();
		Author sessionAuthor = this.getSessionAuthor(request);
		Book findBook = new Book();
		findBook.setAuthorId(sessionAuthor.getAuthorId());
		findBook.setBookId(book.getBookId());
		findBook.setBookFlag(-1);
		List<Book> bookList = bookService.findBook(findBook);
		attrMap.put("bookId", book.getBookId());
		if (bookList.size() == 1) {
			List<Category> categoryList = categoryService.findChildCategory();
			List<Tag> tagList = tagService.findTag(new Tag());
			attrMap.put("categoryList", categoryList);
			attrMap.put("tagList", tagList);
			attrMap.put("book", bookList.get(0));
			attrMap.put("sourceUrl", Constants.SOURCE_URL);
			BookTag findBookTag = new BookTag();
			findBookTag.setBookId(book.getBookId());
			List<BookTag> bookTagList = bookTagService.findBookTag(findBookTag);
			for (Tag t : tagList) {
				for (BookTag bt : bookTagList) {
					if (t.getTagId() == bt.getTagId()) {
						t.setIsSelect(1);// 已经选择
						break;
					}
				}
			}
			attrMap.put("bookTagList", bookTagList);
			return this.packModeAndView(request, "/bookEdit", null, attrMap);
		} else {
			return this.packModeAndView(request, "/error", "非法操作！", null);
		}

	}

	@Transactional
	@RequestMapping("update")
	public String bookUpdate(HttpServletRequest request, HttpServletResponse response, Book book, Model model) {
		Map<String, Object> attrMap = new HashMap<String, Object>();
		Author sessionAuthor = this.getSessionAuthor(request);
		Book updateBook = new Book();
		updateBook.setBookId(book.getBookId());
		updateBook.setAuthorId(sessionAuthor.getAuthorId());
		updateBook.setBookDesc(book.getBookDesc());
		updateBook.setBookCategoryId(book.getBookCategoryId());
		bookService.updateBook(updateBook);

		// 保存书籍标签
		if (!StringUtil.isNullOrEmpty(book.getTagIds())) {
			// 删除旧的书籍标签
			BookTag deleteBookTag = new BookTag();
			deleteBookTag.setBookId(book.getBookId());
			bookTagService.deleteBookTag(deleteBookTag);
			String[] tagArray = book.getTagIds().split(",");
			for (int i = 0; i < tagArray.length; i++) {
				BookTag insertBookTag = new BookTag();
				insertBookTag.setBookId(book.getBookId());
				insertBookTag.setTagId(Integer.valueOf(tagArray[i]));
				bookTagService.insertBookTag(insertBookTag);
			}
		}
		return this.packStringView(request, "redirect:/book/detail?bookId=" + book.getBookId(), null, model);
	}

	@RequestMapping("/cover")
	public ModelAndView coverList(HttpServletRequest request, HttpServletResponse response, Page page) {
		Map<String, Object> attrMap = new HashMap<String, Object>();
		Author sessionAuthor = this.getSessionAuthor(request);
		Book findBook = new Book();
		findBook.setAuthorId(sessionAuthor.getAuthorId());
		findBook.setBookFlag(-1);// 查询完结或未完结的书籍
		page.setLimit(5);
		findBook.setLimit(page.getLimit());
		findBook.setPageNo(page.getPageNo());
		List<Book> bookList = bookService.findBook(findBook);
		int count = bookService.countBook(findBook);
		attrMap.put("bookList", bookList);
		attrMap.put("recordCount", count);
		attrMap.put("page", page);
		attrMap.put("pageftl", new PageDirective(request));
		attrMap.put("sourceUrl", Constants.SOURCE_URL);
		return this.packModeAndView(request, "/bookCover", null, attrMap);
	}

	@RequestMapping("/updateDefCover")
	@ResponseBody
	public String updateBookDefCover(HttpServletRequest request, HttpServletResponse response, Page page) {
		Author sessionAuthor = this.getSessionAuthor(request);
		String bookId = request.getParameter("bookId");
		String defaultCover = request.getParameter("defaultCover");
		JSONObject resultObj = new JSONObject();
		try {
			Book updateBook = new Book();
			updateBook.setAuthorId(sessionAuthor.getAuthorId());
			updateBook.setBookId(Integer.valueOf(bookId));
			updateBook.setBookImageType(0);
			if (defaultCover.equals("2")) {
				updateBook.setBookImage("default/cover_2.jpg");
			} else if (defaultCover.equals("3")) {
				updateBook.setBookImage("default/cover_3.jpg");
			} else {
				updateBook.setBookImage("default/cover_1.jpg");
			}
			bookService.updateBookDefCover(updateBook);
			resultObj.put("code", 0);
			resultObj.put("url", request.getContextPath() + "/book/cover?pageNo=" + this.getLastPageNo(request));
			resultObj.put("message", "修改书籍默认封面成功！");
		} catch (Exception e) {
			resultObj.put("code", -1);
			resultObj.put("message", "修改书籍默认封面错误！");
		}

		return resultObj.toString();
	}

//	@RequestMapping("/uploadCover")
//	public String bookUpdate(@RequestParam(value = "fileContent", required = false) MultipartFile multipartFile,
//			HttpServletRequest request, Book book, Model model) {
//		try {
//			if (multipartFile != null) {
//				if (!multipartFile.isEmpty()) {
//					if (multipartFile.getSize() > 1024 * 40) {
//						return this.packStringView(request, "/error", "上传图片超出限制，请上传30kb以内的jpg图片！", model);
//					}
//					if (!multipartFile.getContentType().equals("image/jpeg")) {
//						return this.packStringView(request, "/error", "上传图片格式错误，请上传30kb以内的jpg图片！", model);
//					}
//					Author sessionAuthor = this.getSessionAuthor(request);
//
//					String suffix = multipartFile.getOriginalFilename()
//							.substring(multipartFile.getOriginalFilename().lastIndexOf("."));
//					String fileName = StringUtil.createNumberUUID() + suffix;
//					// Calendar a = Calendar.getInstance();
//					// String path = File.separator + a.get(Calendar.YEAR) +
//					// File.separator + (a.get(Calendar.MONTH) + 1)+
//					// File.separator
//					// + a.get(Calendar.DAY_OF_MONTH);
//					// String filePath = Configure.uploadPath + File.separator +
//					// Configure.uploadProject + path;
//					String path = request.getSession().getServletContext().getRealPath(File.separator);
//					String filePath = path + File.separator + "image" + File.separator + "book";
//					File targetFile = new File(filePath, fileName);
//					if (!targetFile.exists()) {
//						targetFile.mkdirs();
//					}
//					// 删除旧图片
//					File oldFile = new File(path + File.separator + book.getBookImage());
//					if (oldFile.exists()) {
//						oldFile.delete();
//					}
//					book.setBookImageType(0);// 修改图片后，图片类型为本地图片。
//					// 保存
//					multipartFile.transferTo(targetFile);
//					// 修改图片上传至资源服务器2017-06-15
//					CloseableHttpClient httpclient = HttpClients.createDefault();
//					HttpPost httpPost = new HttpPost("http://resource.sxyd8.com/srvapifile/user/uploadFile");
//					httpPost.setHeader("systemId", "resource");
//					httpPost.setHeader("projectId", "P201704051440251503135");
//					String timestamp = StringUtil.getTimestamp();
//					httpPost.setHeader("timestamp", timestamp);
//					httpPost.setHeader("secretId", "NjdjNDcx");
//					httpPost.setHeader("version", "1.0.0");
//					httpPost.setHeader("platform", "2");
//					String randomKey = StringUtil.createNumberUUID();
//					httpPost.setHeader("randomKey", randomKey);
//					JSONObject dataObjRe = new JSONObject();
//					dataObjRe.put("categoryDir", "book");
//
//					System.out.println(dataObjRe.toString());
//					String dataRe = DES3.encode(dataObjRe.toString().getBytes("utf-8"),
//							"c5e110477f7ab35027743d36faf61e3c");
//					System.out.println(dataRe.toString());
//					httpPost.setHeader("data", dataRe);
//					String signature = Md5Util.md5Encode("resource" + "P201704051440251503135" + timestamp + "NjdjNDcx"
//							+ "1.0.0" + "2" + randomKey + dataRe + "ZTA3MWZjMGQ0MTliYT");
//					httpPost.setHeader("signature", signature);
//					MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//					builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//					builder.setCharset(CharsetUtils.get("UTF-8"));
//
//					// File file = new
//					// File("/data/www/resource_file/temp/booktemp.jpg");
//					// File file = new File("f://temp/booktemp.jpg");
//					FileBody bin = new FileBody(targetFile);
//					builder.addPart("image", bin);// uploadFile对应服务端类的同名属性<File类型>
//
//					// StringBody uploadFileName = new StringBody("my.png",
//					// Consts.UTF_8);
//					// builder.addPart("uploadFileName", uploadFileName);////
//					// uploadFileName对应服务端类的同名属性<String类型>
//					HttpEntity reqEntity = builder.build();
//					httpPost.setEntity(reqEntity);
//
//					CloseableHttpResponse response = httpclient.execute(httpPost);
//					HttpEntity entity = response.getEntity();
//					String result = EntityUtils.toString(entity, "utf-8");
//					String resultDes = DES3.decode(result.getBytes("utf-8"), "c5e110477f7ab35027743d36faf61e3c");
//					logger.info(resultDes);
//					JSONObject reObj = JSONObject.fromObject(resultDes);
//					int reStatus = reObj.optInt("status", 1);
//					if (reStatus == 0) {
//						JSONObject reDataObj = reObj.optJSONObject("data");
//						JSONArray reArray = reDataObj.optJSONArray("fileUrlList");
//						if (reArray.size() >= 1) {
//							JSONObject fObj = reArray.getJSONObject(0);
//							// 更新书籍封面
//							// Book updateBook = new Book();
//							// updateBook.setBookId(b.getBookId());
//							book.setBookImage(fObj.optString("filePath", ""));
//							book.setBookImageType(0);// 书籍封面：：默认0，0官方图片上传，1第三方平台图片链接
//							// bookService.updateBookImage(updateBook);
//						}
//					}
//					// book.setBookImage("image" + File.separator + "book" +
//					// File.separator + fileName);
//					book.setAuthorId(sessionAuthor.getAuthorId());
//					bookService.uploadBookCover(book);
//				}
//
//				else {
//					return this.packStringView(request, "/error", "上传图片为空！", model);
//				}
//			}
//
//		} catch (Exception e) {
//			logger.info("upload book image error=" + e.toString());
//		}
//		String opType = request.getParameter("opType");
//		if ("book".equals(opType)) {
//			return "redirect:/book/cover?pageNo=" + this.getLastPageNo(request);
//		} else {
//			return "redirect:/author/index?pageNo=" + this.getLastPageNo(request);
//		}
//
//	}
	/**
	 * 前置条件maven添加7牛sdk
	 * @param multipartFile
	 * @param request
	 * @param book
	 * @param model
	 * @return
	 */
	@RequestMapping("/uploadCover")
	public String bookUpdate(@RequestParam(value = "fileContent", required = false) MultipartFile multipartFile,
			HttpServletRequest request, Book book, Model model) {
		try {
			if (multipartFile != null) {
				if (!multipartFile.isEmpty()) {
					Author sessionAuthor = this.getSessionAuthor(request);
					String suffix = multipartFile.getOriginalFilename()
					.substring(multipartFile.getOriginalFilename().lastIndexOf("."));
					String fileName = StringUtil.createNumberUUID() + suffix;
					//构造一个带指定Zone对象的配置类
					Configuration cfg = new Configuration(Zone.zone0());
					//...其他参数参考类注释
					UploadManager uploadManager = new UploadManager(cfg);
					//...生成上传凭证，然后准备上传
				    String accessKey = "TyPdL61ticgTc9ks6kuAoWx-NzyNd_QpjlzBiMp8";
				    String secretKey = "Kt56XOpf7-nzrgOH1gDheJYUv_8IBDlL-EkhdzfQ";
				    String bucket = "reader-bucket";
				    //默认不指定key的情况下，以文件内容的hash值作为文件名
				    String key = fileName;
				    try {
				        byte[] uploadBytes = multipartFile.getBytes();
				        Auth auth = Auth.create(accessKey, secretKey);
				        String upToken = auth.uploadToken(bucket);
				        try {
				            Response response = uploadManager.put(uploadBytes, key, upToken);
				            //解析上传成功的结果
				            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
				        } catch (QiniuException ex) {
				            Response r = ex.response;
				            System.err.println(r.toString());
				            try {
				                System.err.println(r.bodyString());
				            } catch (QiniuException ex2) {
				                //ignore
				            }
				        }
				    } catch (UnsupportedEncodingException ex) {
				        //ignore
				    }
					
					book.setBookImage(Constants.IMAGE_URL+key);
					book.setBookImageType(1);// 书籍封面：：默认0，0官方图片上传，1第三方平台图片链接
					book.setAuthorId(sessionAuthor.getAuthorId());
					bookService.uploadBookCover(book);
				}
				else {
					return this.packStringView(request, "/error", "上传图片为空！", model);
				}
			}
		} catch (Exception e) {
			logger.info("upload book image error=" + e.toString());
		}
		String opType = request.getParameter("opType");
		if ("book".equals(opType)) {
			return "redirect:/book/cover?pageNo=" + this.getLastPageNo(request);
		} else {
			return "redirect:/author/index?pageNo=" + this.getLastPageNo(request);
		}

	}
}
